import { ref } from 'vue';
import { defineStore } from 'pinia';

// 初始状态的默认值
const defaultFocusEchartItem = {
  domId: '',
  drawingId: '',
  option: {},
};

export const useJnpfUniverStore = (id: string) => {
  return defineStore(id, () => {
    // 组件模式
    const modeCache: any = ref(null);
    // 整个api实例
    const jnpfUniverApiCache: any = ref(null);
    // 当前工作表中所有的图表信息
    const echartItemsCache: Record<string, any> = ref({});
    // 当前工作表中所有的图表图片信息
    const echartImgItemsCache: Record<string, any> = ref({});
    // 当前选中图表的缓存，包含 DOM ID、绘图 ID 和配置
    const focusEchartItemCache = ref({ ...defaultFocusEchartItem });

    /**
     * 更新组件模式
     * @param type
     */
    const updateModeCache = (type: string) => {
      modeCache.value = type;
    };

    /**
     * 存储jnpfUniverApi
     * @param value
     */
    const updateJnpfUniverApi = (value: any) => {
      jnpfUniverApiCache.value = value ?? null;
    };

    /**
     * 更新图表列表
     * @param value
     */
    const updateEchartItems = (value: any) => {
      echartItemsCache.value = value;
      jnpfUniverApiCache.value?.getSheetsEchart()?.saveEchartItems(value);
    };

    /**
     * 更新图表图片列表
     * @param value
     */
    const updateEchartImgItems = (value: any) => {
      echartImgItemsCache.value = value;
    };

    /**
     * 更新指定图表的缓存信息，并同步更新当前选中图表的缓存
     * @param deliverConfig
     */
    const updateFocusEchartItem = (deliverConfig: any) => {
      focusEchartItemCache.value = deliverConfig ?? {};
    };

    /**
     * 根据drawingId获取图表信息
     * @param drawingId
     */
    const getEchartItemByDrawingId = (drawingId: string) => {
      return echartItemsCache.value?.[drawingId] ?? null;
    };

    /**
     * 重置存储状态为初始值
     */
    const resetStore = () => {
      modeCache.value = null;
      jnpfUniverApiCache.value = null;
      echartItemsCache.value = {};
      echartImgItemsCache.value = {};
      focusEchartItemCache.value = defaultFocusEchartItem;
    };

    return {
      modeCache,
      echartItemsCache,
      echartImgItemsCache,
      focusEchartItemCache,
      updateJnpfUniverApi,
      updateEchartItems,
      updateEchartImgItems,
      updateModeCache,
      updateFocusEchartItem,
      getEchartItemByDrawingId,
      resetStore,
    };
  })();
};
